package com.quasar.hpatient.module.doctor_chat;


import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.quasar.hpatient.R;
import com.quasar.hpatient.api.HttpClient;
import com.quasar.hpatient.api.HttpParams;
import com.quasar.hpatient.bean.comm_album.AlbumPhotoBean;
import com.quasar.hpatient.bean.doctor_chat.ChatMenuBean;
import com.quasar.hpatient.module.comm_album.AlbumActivity;
import com.quasar.hpatient.module.home_inspection.HomeInspectionActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import lib.quasar.base.frame.BasePresenter;
import lib.quasar.base.frame.OnModelAcceptChangeListener;
import lib.quasar.base.frame.OnModelChangeListener;
import lib.quasar.base.http.HttpResult;
import lib.quasar.chat.ChatModel;
import lib.quasar.chat.ChatService;
import lib.quasar.compress.CompressManager;
import lib.quasar.compress.OnCompressChangeListener;
import lib.quasar.context.BaseApp;
import lib.quasar.context.BaseConstant;
import lib.quasar.db.manager.DBManager;
import lib.quasar.db.table.Chat;
import lib.quasar.db.table.User;
import lib.quasar.recycler.BaseCommonMultAdapter;
import lib.quasar.recycler.holder.RecyclerHolder;
import lib.quasar.recycler.manager.CrashLinearLayoutManager;
import lib.quasar.recycler.manager.CrashPagerGridLayoutManager;
import lib.quasar.recycler.model.MultModel;
import lib.quasar.util.CardUtil;
import lib.quasar.util.ImageUtil;
import lib.quasar.util.LogUtil;
import lib.quasar.util.ToastUtil;
import lib.quasar.widget.emoji.EmojiLayout;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * description: 聊天
 * created by kalu on 2018/6/11 22:59
 */
public final class DoctorChatPresenter implements BasePresenter {

    private final LinkedList<ChatMenuBean> menuDatas = new LinkedList<>();
    private final CrashPagerGridLayoutManager menuManager = new CrashPagerGridLayoutManager(2, 4, CrashPagerGridLayoutManager.HORIZONTAL);
    private final CrashPagerGridLayoutManager emojManager = new CrashPagerGridLayoutManager(4, 8, CrashPagerGridLayoutManager.HORIZONTAL);

    private final LinkedList<Chat> mDates = new LinkedList();
    private BroadcastReceiver reciveMessage;

    final void loadMessage(DoctorChatView view, String doctorid) {
        final User user = DBManager.getInstance().syncGetUserModel();
        List<Chat> chatList = DBManager.getInstance().getChatList(user.getPatientid(), Long.parseLong(doctorid));
        mDates.clear();
        mDates.addAll(chatList);
    }

    final void initBroadcast(DoctorChatView view, RecyclerView recycler, String doctorid) {

        reciveMessage = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                if (null == recycler || TextUtils.isEmpty(doctorid))
                    return;

                final RecyclerView.Adapter adapter = recycler.getAdapter();
                if (null == adapter)
                    return;


//                ((sendid != Long.parseLong(doctorid)) &&|| (sendid != patientid)
                final Chat messageModel = (Chat) intent.getSerializableExtra(ChatService.MESSAGE_MODEL);
                long Doctor = Long.parseLong(doctorid);
                Long sendid = messageModel.getSendid();
                Long recieveid = messageModel.getReceiveid();

                LogUtil.e("DoctorChatPresenter", "initBroadcast ==> doctorid = " + doctorid + ", message = " + messageModel.toString());
                if ((null == messageModel)|| ((sendid.longValue() != Doctor) && (recieveid.longValue() != Doctor)) )
                    return;

                mDates.addLast(messageModel);
                view.refreshList(recycler);
                recycler.scrollToPosition(adapter.getItemCount() - 1);
            }
        };
        // 接收消息
        LocalBroadcastManager.getInstance(BaseApp.getContext()).registerReceiver(reciveMessage, new IntentFilter(ChatService.INTENT_NAME));
    }

    final void initList(DoctorChatView view, RecyclerView recycler, EmojiLayout emoji) {

        if (null == view || null == recycler)
            return;

        final CrashLinearLayoutManager manager = new CrashLinearLayoutManager(BaseApp.getContext());

        final BaseCommonMultAdapter mAdapter = new BaseCommonMultAdapter<Chat>(mDates) {

            @Override
            protected void onRoll(RecyclerView recycler, int itemHeight, int rollHeight, int rollState, int fistVisablePosition, int lastVisablePosition) {
                emoji.closeMenu();
            }

            @Override
            protected void onMult() {
                addMult(MultModel.TYPE_0, R.layout.activity_patient_chat_child_text_right);
                addMult(MultModel.TYPE_1, R.layout.activity_patient_chat_child_image_right);
                addMult(MultModel.TYPE_2, R.layout.activity_patient_chat_child_inspection_right);
                addMult(MultModel.TYPE_3, R.layout.activity_patient_chat_child_text_left);
                addMult(MultModel.TYPE_4, R.layout.activity_patient_chat_child_image_left);
                addMult(MultModel.TYPE_5, R.layout.activity_patient_chat_child_inspection_left);
            }

            @Override
            protected void onNext(RecyclerHolder holder, Chat model, int position) {

                String mType = model.getMessage_type();
                if (Chat.DIAGNOSE.equals(mType)||Chat.ADVISE.equals(mType)) {
                    String inspectionDiagnose = model.getJson_message_content();
                    ChatModel.InspectionAll inspectionAll = new Gson().fromJson(inspectionDiagnose, ChatModel.InspectionAll.class);
                    if (null != inspectionAll) {

                        Log.e("WebSocketService", model.getSend_type() + "");
                        if (model.getSend_type() == 0) {
                            holder.setText(R.id.patient_chat_child_inspection, model.getSend_name() + "诊疗了您的化验单,并回复了您!" +inspectionAll.getRecord_content()+
                                    "\r\n" + "时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
                        } else if (model.getSend_type() == 1){
                            holder.setText(R.id.patient_chat_child_inspection, model.getMessage() +inspectionAll.getRecord_content()+
                                    "\r\n" + "时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
                        }

                        holder.itemView.setOnClickListener(v -> {
                            Intent intent = new Intent();
                            intent.setClass(BaseApp.getContext(), HomeInspectionActivity.class);
                          /* intent.putExtra(PatientListActivity.SELECT_POSITION, 0);
                            intent.putExtra(PatientListActivity.PATIENT_ID, inspectionModel.getPatientid());
                            intent.putExtra(PatientListActivity.PATIENT_NAME, model.getSend_name());*/
                            String[] time = inspectionAll.getInspection_date().split(" ");
                            intent.putExtra("time", time[0]);
                            view.goNext(intent);
                        });
                    }}else if (Chat.INSPECTION.equals(mType)) {
                    String inspectionJson = model.getJson_message_content();
                    ChatModel.InspectionModel inspectionModel = new Gson().fromJson(inspectionJson, ChatModel.InspectionModel.class);
                    if (null != inspectionModel) {

                        Log.e("WebSocketService", model.getSend_type() + "");
                        if (model.getSend_type() == 0) {
                            holder.setText(R.id.patient_chat_child_inspection, model.getSend_name() + "替你修改了化验单!" +
                                    "\r\n" + "时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
                        } else if (model.getSend_type() == 1){
                            holder.setText(R.id.patient_chat_child_inspection, "您向" + model.getReceive_name() + "发送了化验单!" +
                                    "\r\n" + "时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
                        }

                        holder.itemView.setOnClickListener(v -> {
                            Intent intent = new Intent();
                            intent.setClass(BaseApp.getContext(), HomeInspectionActivity.class);
                          /* intent.putExtra(PatientListActivity.SELECT_POSITION, 0);
                            intent.putExtra(PatientListActivity.PATIENT_ID, inspectionModel.getPatientid());
                            intent.putExtra(PatientListActivity.PATIENT_NAME, model.getSend_name());*/
                            String[] time = inspectionModel.getInspection_date().split(" ");
                            intent.putExtra("time", time[0]);
                            view.goNext(intent);
                        });
                    }
                } else if (Chat.PICTURE.equals(model.getMessage_type())) {
                    view.setImage(holder, R.id.patient_chat_child_image, model.getUrls());

                    holder.setOnClickListener(R.id.patient_chat_child_image, v -> {

                        final LinkedList<ImageView> viewList = new LinkedList();
                        final ImageView image = (ImageView) v;
                        final LinkedList<Chat> imageDatas = new LinkedList();
                        final int firstVisiblePosition = manager.findFirstVisibleItemPosition();
                        final int lastVisiblePosition = manager.findLastVisibleItemPosition();

                        for (int i = 0; i < mDates.size(); i++) {
                            final Chat it = mDates.get(i);
                            if (!it.isPicture()) continue;
                            final int index = mDates.indexOf(it);
                            imageDatas.add(it);
                            if (index < firstVisiblePosition || index > lastVisiblePosition) {
                                viewList.add(image);
                            } else {
                                final ImageView picture = manager.findViewByPosition(index).findViewById(R.id.patient_chat_child_image);
                                viewList.add(picture);
                            }
                        }
                        view.showPhoto(imageDatas.indexOf(model), imageDatas, imageDatas, viewList);
                    });

                } else if (Chat.MESSAGE.equals(model.getMessage_type())) {
                    // view.setText(holder, R.id.patient_chat_child_message, model.getJson_message_content());
                    view.setText(holder, R.id.patient_chat_child_message, model.getJson_message_content());
                }

            }
        };
        mAdapter.setNullView(BaseApp.getContext(), R.layout.layout_recycler_loading);
        view.setRecycler(recycler, mAdapter, manager);
        // 将recycler滚动到最底部
        recycler.scrollToPosition(mAdapter.getItemCount() - 1);
    }

    final void sendMessage(DoctorChatView view, RecyclerView recycler, String message, String messageType, String doctorId, String doctorName) {

        if (null == view || null == recycler)
            return;

        final RecyclerView.Adapter adapter = recycler.getAdapter();
        if (null == adapter)
            return;

        final String clientId = getClientId();
        if (TextUtils.isEmpty(doctorName) || TextUtils.isEmpty(doctorId) || TextUtils.isEmpty(clientId)) {
            ToastUtil.showToast("好友信息初始化失败");
            return;
        }
        HashMap<String, Object> map = new HashMap();
        map.put("sendtotype", "d");
        map.put("sendertype", "p");
        map.put("sendto", doctorId);
        map.put("sendid", DBManager.getInstance().syncGetUserModel().getPatientid());
        map.put("client_id", clientId);
        Chat messageBean = new Chat();
        messageBean.setSendid(DBManager.getInstance().syncGetUserModel().getPatientid());
        messageBean.setSend_name(DBManager.getInstance().syncGetUserModel().getReal_name());
        messageBean.setReceiveid(Long.parseLong(doctorId));
        messageBean.setReceive_name(doctorName);
        messageBean.setMessage_type(messageType);
        messageBean.setMessage(message);
        messageBean.setJson_message_content(message);
        messageBean.setSend_datetime(getSecond());
        messageBean.setRead_datetime(getSecond());
        messageBean.setSend_type(1);
        messageBean.setStatus(0);
        map.put("datas", messageBean);


        RequestBody params = createParams(map, HttpParams.DATA_TYPE_9);
        Observable<HttpResult<Object>> observable = HttpClient.getSingleHolder().getHttpService().uploadData(params);
        request(observable, new OnModelChangeListener() {
            @Override
            public void modelFail() {
                view.toast("发送消息失败");
            }

            @Override
            public void modelSucc() {
                //存入数据库
                DBManager.getInstance().insertChat(messageBean);
                mDates.addLast(messageBean);
                view.refreshList(recycler);
                recycler.scrollToPosition(adapter.getItemCount() - 1);
                view.toast("发送消息成功");
            }
        });
    }

    @Override
    public void recycler() {
        if (null == reciveMessage) return;
        LocalBroadcastManager.getInstance(BaseApp.getContext()).unregisterReceiver(reciveMessage);
    }

    @SuppressLint("CheckResult")
    final void compressImage(DoctorChatView view, RecyclerView recycler, ArrayList<AlbumPhotoBean> list, String doctoeId, String doctorName) {
        if (list.isEmpty())
            return;
        Observable.create((ObservableOnSubscribe<ArrayList<AlbumPhotoBean>>) emitter -> {
            final ArrayList<AlbumPhotoBean> temp = new ArrayList<>();
            // 压缩, 保存图片
            for (int i = 0; i < list.size(); i++) {
                final AlbumPhotoBean image = list.get(i);
                String path = image.getPicture();
                String name = path.substring(path.lastIndexOf(File.separatorChar), path.length());
                final int width = image.getWidth();
                final int height = image.getHeight();
                final long size = image.getSize();
                // 获取bitmap
                if (!image.needCompress()) {
                    final AlbumPhotoBean news = new AlbumPhotoBean();
                    news.setPicture(path);
                    news.setCheck(image.isCheck());
                    news.setWidth(width);
                    news.setHeight(height);
                    news.setSize(size);
                    temp.clear();
                    temp.add(news);
                    emitter.onNext(temp);
                } else {
                    final Bitmap bitmap = ImageUtil.compressImageJava(path, image.calcuWidth(), image.calcuHeight());
                    final String floder = CardUtil.getSDCardPath() + BaseConstant.CACHE_COMPRESS;

                    // 压缩图片
                    CompressManager.syncCompress(true, image.getRatio(), floder, name, bitmap, new OnCompressChangeListener() {
                        @Override
                        public void onCompressStart() {
                        }

                        @Override
                        public void onCompressFinish(String filePath) {

                            if (null != bitmap) {
                                bitmap.recycle();
                                LogUtil.e("", "onCompressFinish ==> 释放bitmap");
                            }

                            AlbumPhotoBean news = new AlbumPhotoBean();
                            news.setPicture(filePath);
                            news.setCheck(image.isCheck());
                            news.setWidth(width);
                            news.setHeight(height);
                            news.setSize(size);

                            temp.clear();
                            temp.add(news);
                            emitter.onNext(temp);
                            LogUtil.e("iiiiu", "onCompressFinish ==> filePath = " + filePath);
                        }

                        @Override
                        public void onCompressError(int errorNum, String description) {

                            if (null != bitmap) {
                                bitmap.recycle();
                                LogUtil.e("", "onCompressError ==> 释放bitmap");
                            }
                            LogUtil.e("iiiiu", "onCompressError ==> errorNum = " + errorNum + ", description = " + description);
                        }
                    });
                }
            }
        }).subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(news -> {
                    uploadPhoto(view, recycler, news, doctoeId, doctorName);
                });
    }

    final void uploadPhoto(DoctorChatView view, RecyclerView recycler, ArrayList<AlbumPhotoBean> model, String doctoeId, String doctorName) {

        if (null == recycler) return;
        LinkedList<AlbumPhotoBean> upList = new LinkedList<AlbumPhotoBean>();
        upList.addAll(model);

        final HashMap<String, RequestBody> request = new HashMap<String, RequestBody>();
        for (int x = 0; x < upList.size(); x++) {
            String imagePath = upList.get(x).getPicture();
            File file = new File(imagePath);
            RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            request.put("file" + x + "\"; filename=\"" + file.getName() + "\"", body);
          //  LogUtil.e("iiiiu", "file" + x + "\"; filename=\"" + file.getName() + "\"" + "======" + body);
        }

        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.INSPECTIONDATE, getDate());
        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_412);
        final Observable<HttpResult<List<AlbumPhotoBean>>> observable = HttpClient.getSingleHolder().getHttpService().uploadPhoto(params, request);

        request(observable, new OnModelAcceptChangeListener<List<AlbumPhotoBean>>() {
            @Override
            public void modelSucc(List<AlbumPhotoBean> list) {
                for (int x = 0; x < list.size(); x++) {
                    sendMessage(view, recycler, list.get(x).getPicture(), "picture", doctoeId, doctorName);
                }
            }
        });
    }

    final void initMenuAdapter(DoctorChatView view, RecyclerView menuRecycler) {

        menuDatas.clear();
        ChatMenuBean menu1 = new ChatMenuBean();
        menu1.setMenuIcon(String.valueOf(R.drawable.ic_chat_menu_camera));
        menu1.setMenuText("拍摄");
        menuDatas.addLast(menu1);
        ChatMenuBean menu2 = new ChatMenuBean();
        menu2.setMenuIcon(String.valueOf(R.drawable.ic_chat_menu_album));
        menu2.setMenuText("图片");
        menuDatas.addLast(menu2);

        final BaseCommonMultAdapter adapter = new BaseCommonMultAdapter<ChatMenuBean>(menuDatas) {
            @Override
            protected void onMult() {
                addMult(MultModel.TYPE_1, R.layout.activity_doctor_chat_type_emoji);
                addMult(MultModel.TYPE_2, R.layout.activity_doctor_chat_type_menu);
            }

            @Override
            protected void onNext(RecyclerHolder holder, ChatMenuBean model, int position) {

                if (model.isEmoji()) {
                    view.setImage(holder, R.id.doctor_chat_type_menu_icon, model.getMenuIcon());
                } else {
                    view.setText(holder, R.id.doctor_chat_type_menu_info, model.getMenuText());
                    view.setImage(holder, R.id.doctor_chat_type_menu_icon, Integer.parseInt(model.getMenuIcon()));
                }

                holder.setOnClickListener(R.id.doctor_chat_type_menu_icon, v -> {
                    if (model.isEmoji()) {

                    } else if (model.isCamera()) {
                        view.goNextResult(AlbumActivity.class, DoctorChatActivity.REQUEST_CODE);
                    } else {
                        view.goNextResult(AlbumActivity.class, DoctorChatActivity.REQUEST_CODE);
                    }
                });
            }
        };

        final CrashPagerGridLayoutManager.PagerGridSnapHelper snapHelper = new CrashPagerGridLayoutManager.PagerGridSnapHelper();
        view.setRecycler(menuRecycler, adapter, menuManager, snapHelper);
    }
}